#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils import log
from sqlalchemy.orm import mapper, sessionmaker
from datetime import datetime
from sqlalchemy import Table, MetaData, Column, ForeignKey, Integer, BigInteger, String, Unicode, UnicodeText, DateTime
from controls.data_pool_mysql import engine

# 创建到数据库的连接,echo=True表示用logging输出调试结果
metadata = MetaData()
Session = sessionmaker()  # 创建了一个自定义了的 Session类
Session.configure(bind=engine)  # 将创建的数据库连接关联到这个session

"""img_base collection has 
   imgid:       图片id (int)
   group:       group (int)
   path:        M打头的不含扩展名和从文件名的文件名 (str)
   ext:         扩展名
   sizetype:        图片尺寸类型
   ctime:       添加时间(datetime)

注：
sizetype类型：
    0：只有原图  #目前有可
    1：原图，100，300
"""


class ImgBaseItem(object):  # 创建一个映射类

    def to_dict(self):
        res = {}
        res['imgid'] = self.imgid
        res['group'] = int(self.group)
        res['path'] = self.path
        res['ext'] = self.ext
        res['sizetype'] = self.sizetype
        res['ctime'] = self.ctime
        return res

    def to_url(self):
        url = 'http://static.shitouren.com/group' + str(self.group) + '/' + self.path + '.' + self.ext
        return url

    def __repr__(self):
        return "%d" % (self.imgid)


img_base_table = Table(
    'img_base', metadata,
    Column('id', Integer, primary_key=True),
    Column('imgid', Integer, index=True, unique=True, nullable=False),
    Column('group', Integer, nullable=False),
    Column('path', Unicode(127), nullable=False),
    Column('ext', Unicode(63), nullable=False),
    Column('sizetype', Integer, nullable=False, default=1),
    Column('ctime', DateTime, default=datetime.now, nullable=False),
)

mapper(ImgBaseItem, img_base_table)  # 把表映射到类


def create_img_base_table_if_not_exist():
    metadata.create_all(engine)  # 在数据库中生成表


def add_img_base_item(p_item):
    item = ImgBaseItem()
    item.imgid = p_item['imgid']
    item.group = p_item['group']
    item.path = p_item['path']
    item.ext = p_item['ext']
    item.sizetype = p_item['sizetype']
    try:
        session = Session()
        session.add(item)  # 往session中添加内容
        session.flush()  # 保存数据
        session.commit()  # 数据库事务的提交,sisson自动过期而不需要关闭
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()
        # session.remove()


def get_img_base_by_imgid(p_imgid):
    try:
        session = Session()
        item = session.query(ImgBaseItem).filter_by(imgid=p_imgid).first()
        if not item:
            return None
        return item.to_dict()
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()
        # session.remove()


def get_img_url_by_imgid_list(p_img_list):
    try:
        session = Session()
        items = session.query(ImgBaseItem).filter(ImgBaseItem.imgid.in_(p_img_list)).all()
        if not items:
            return {}
        res = {}
        for item in items:
            res[item.imgid] = item.to_url()
        return res
    except Exception as e:
        log.exp(e)
        return {}
    finally:
        session.close()


def get_img_url_by_imgid(p_img_id):
    try:
        session = Session()
        item = session.query(ImgBaseItem)\
            .filter(ImgBaseItem.imgid == p_img_id).first()
        if not item:
            return None
        return item.to_url()
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()


def delete_img_base_by_imgid_list(p_imgid_list):
    try:
        session = Session()
        session.query(ImgBaseItem).filter(ImgBaseItem.imgid.in_(p_imgid_list)).delete(synchronize_session=False)
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


def delete_img_base_by_imgid(p_imgid):
    try:
        session = Session()
        session.query(ImgBaseItem).filter_by(imgid=p_imgid).delete()
        session.flush()  # 保存数据
        session.commit()  # 数据库事务的提交,sisson自动过期而不需要关闭
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()
        # session.remove()


if __name__ == "__main__":
    create_img_base_table_if_not_exist()
    item1 = {'imgid': 1234, 'group': 1, 'path': 'M00/00/00/0g6asVUlhsGAH4NTAAfYzBjHljI331', 'ext': 'jpg'}
    add_img_base_item(item1)
